import { Button, Checkbox, Form, Icon, Input, Modal, Result } from "antd";
import { WrappedFormUtils } from "antd/lib/form/Form";
import * as React from "react";
import { connect } from "react-redux";
import { RouteComponentProps, withRouter } from "react-router";
import { Dispatch } from "redux";
import { Reducers } from "../../../App";
import { setLoginModalVisibleAct } from "../../store/actions";
import { ILoginForm, loginAction } from "../../pages/login/login";
import { mobile } from "../../config/regexp";

const { Item } = Form;
interface IProps extends RouteComponentProps {
  show?: boolean;
  setLoginModalVisible?: Function;
  form: WrappedFormUtils;
}

const STYLES = {
  iconStyle: { color: "rgba(0,0,0,.25)" },
  submitBtnStyle: { width: "100%" }
};
// when token is no auth ,show this
const LoginModal: React.FC<IProps> = props => {
  const { show, form, history } = props;
  const setLoginModalVisible = props.setLoginModalVisible ? props.setLoginModalVisible : (visible: true) => {};
  const { getFieldDecorator } = form;

  const [loading, setLoading] = React.useState<boolean>(false);

  // 登录状态
  const [status, setStatus] = React.useState<boolean>(false);

  // 提交函数
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault(); //阻止跳转
    form.validateFields((err, values) => {
      if (!err) {
        console.log("Received values of form: ", values);
        const formData: ILoginForm = {
          username: values.username,
          password: values.password,
          remember: values.remember
        };
        // 传入History对象
        loginAction(formData, history, setLoading, () => {
          // setLoginModalVisible(false);
          setStatus(true);
        });
      }
    });
  };

  // 登录前的组件
  const beforeLogined = (
    <Form onSubmit={handleSubmit}>
      <Item>
        {getFieldDecorator("username", {
          rules: [
            { required: true, message: "请输入手机号" },
            {
              pattern: RegExp(mobile),
              message: "手机号格式不正确"
            }
          ]
        })(<Input prefix={<Icon type='user' style={STYLES.iconStyle} />} placeholder='手机号' />)}
      </Item>
      <Item>
        {getFieldDecorator("password", {
          rules: [
            { required: true, message: "请输入密码" },
            {
              pattern: new RegExp("^[0-9a-zA-Z_]{6,21}$"),
              message: "密码格式不正确(6~16位，由数字字母下划线组成)"
            }
          ]
        })(<Input placeholder='密码' type='password' prefix={<Icon type='lock' style={STYLES.iconStyle} />} />)}
      </Item>
      <Item>
        {getFieldDecorator("remember", {
          valuePropName: "checked",
          initialValue: true
        })(<Checkbox style={{ float: "left" }}>自动登录</Checkbox>)}
        <span
          className='action'
          style={{ float: "right" }}
          onClick={() => {
            history.replace("/login");
            setLoginModalVisible(false);
          }}>
          去登录页
        </span>
        <Button
          loading={loading}
          type='primary'
          style={STYLES.submitBtnStyle}
          htmlType='submit'
          onClick={(e: React.FormEvent) => {
            // 触发登录
            handleSubmit(e);
          }}>
          登录
        </Button>
      </Item>
    </Form>
  );

  // 登录后的组件
  const afterLogined = (
    <Result
      status='success'
      title='登录成功！'
      subTitle={`登录账户：${form.getFieldValue("username")}`}
      extra={[
        <Button
          onClick={() => {
            setLoginModalVisible(false);
          }}
          key='buy'>
          不需要刷新
        </Button>,
        <Button
          onClick={() => {
            window.location.reload();
          }}
          type='primary'
          key='console'>
          刷新页面
        </Button>
      ]}
    />
  );

  return (
    <Modal
      onOk={() => setLoginModalVisible(false)}
      onCancel={() => setLoginModalVisible(false)}
      destroyOnClose={true}
      maskClosable={false}
      title={status ? "" : "请登录"}
      
      visible={show}>
      {status ? afterLogined : beforeLogined}
    </Modal>
  );
};

const mapStateToProps = (state: Reducers) => ({
  show: state.commonReducer.showLoginModal
});

const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    setLoginModalVisible(visible: boolean) {
      const action = setLoginModalVisibleAct(visible);
      dispatch(action);
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(
  Form.create({ name: "LoginModal" })(
    // 将节点注册到路由中,这样就能获取route的history对象了
    withRouter(LoginModal)
  )
);
